package com.xingongchang.baolebei.model;

import com.insthub.BeeFramework.model.BaseModel;
import com.insthub.BeeFramework.model.BeeCallback;
import com.xingongchang.baolebei.Common;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.protocol.*;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.afinal.simplecache.ACache;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.external.androidquery.callback.AjaxStatus;

public class HomeModel extends BaseModel
{
	public ArrayList<SIMPLEGOODS> simplegoodsList = new ArrayList<SIMPLEGOODS>();
	public ArrayList<CATEGORYGOODS> categorygoodsList = new ArrayList<CATEGORYGOODS>();
	public ArrayList<PLAYER> playersList = new ArrayList<PLAYER>();
	public ArrayList<ShouTu> viewp = new ArrayList<ShouTu>();
	public ArrayList<Tuijian> zuijian = new ArrayList<Tuijian>();
	public ArrayList<News> shudao = new ArrayList<News>();
	public ArrayList<Fen> fen = new ArrayList<Fen>();
	public ArrayList<Home> zuire = new ArrayList<Home>();
	public ArrayList<Advert> adverts = new ArrayList<Advert>();
	String pkName;
	public ProgressDialog pd;
	public String rootpath;
	public STATUS responseStatus;
	public ACache aCache;
	NetworkInfo mNetworkInfo;// 判断网络是否连接

	public HomeModel(Context context)
	{
		super(context);
		pkName = mContext.getPackageName();
		this.mContext = context;
		rootpath = context.getCacheDir() + "/ECMobile/cache";
		aCache = ACache.get(mContext);
		readHomeDataCache();
		readGoodsDataCache();
		// 判断是否连接网络
		ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
	}

	public void readHomeDataCache()
	{

		String path = rootpath + "/" + pkName + "/homeData.dat";
		File f1 = new File(path);
		if (f1.exists())
		{
			try
			{
				InputStream is = new FileInputStream(f1);
				InputStreamReader input = new InputStreamReader(is, "UTF-8");
				BufferedReader bf = new BufferedReader(input);
				homeDataCache(bf.readLine());
				bf.close();
				input.close();
				is.close();

			} catch (FileNotFoundException e)
			{

				e.printStackTrace();
			} catch (UnsupportedEncodingException e)
			{

				e.printStackTrace();
			} catch (IOException e)
			{

				e.printStackTrace();
			}
		}

	}

	public String homeDataCache()
	{
		String path = rootpath + "/" + pkName + "/homeData.dat";
		File f1 = new File(path);
		String s = null;
		if (f1.exists())
		{
			try
			{
				InputStream is = new FileInputStream(f1);
				InputStreamReader input = new InputStreamReader(is, "UTF-8");
				BufferedReader bf = new BufferedReader(input);

				s = bf.readLine();

				bf.close();
				input.close();
				is.close();

			} catch (FileNotFoundException e)
			{

				e.printStackTrace();
			} catch (UnsupportedEncodingException e)
			{

				e.printStackTrace();
			} catch (IOException e)
			{

				e.printStackTrace();
			}
		}

		return s;
	}

	public void readGoodsDataCache()
	{
		String path = rootpath + "/" + pkName + "/goodsData.dat";
		File f1 = new File(path);
		if (f1.exists())
		{
			try
			{
				InputStream is = new FileInputStream(f1);
				InputStreamReader input = new InputStreamReader(is, "UTF-8");
				BufferedReader bf = new BufferedReader(input);

				goodsDataCache(bf.readLine());

				bf.close();
				input.close();
				is.close();

			} catch (FileNotFoundException e)
			{

				e.printStackTrace();
			} catch (UnsupportedEncodingException e)
			{

				e.printStackTrace();
			} catch (IOException e)
			{

				e.printStackTrace();
			}
		}

	}

	public void homeDataCache(String result)
	{

		try
		{
			if (result != null)
			{
				JSONObject jsonObject = new JSONObject(result);

				STATUS responseStatus = STATUS.fromJson(jsonObject
						.optJSONObject("status"));
				if (responseStatus.succeed == 1)
				{
					JSONObject dataJsonObject = jsonObject
							.optJSONObject("data");
					if (null != dataJsonObject)
					{
						JSONArray playerJSONArray = dataJsonObject
								.optJSONArray("player");

						if (null != playerJSONArray
								&& playerJSONArray.length() > 0)
						{
							playersList.clear();
							for (int i = 0; i < playerJSONArray.length(); i++)
							{
								JSONObject playerJsonObject = playerJSONArray
										.getJSONObject(i);
								PLAYER playItem = PLAYER
										.fromJson(playerJsonObject);
								playersList.add(playItem);
							}
						}

						JSONArray simpleGoodsJsonArray = dataJsonObject
								.optJSONArray("promote_goods");

						if (null != simpleGoodsJsonArray
								&& simpleGoodsJsonArray.length() > 0)
						{
							simplegoodsList.clear();
							for (int i = 0; i < simpleGoodsJsonArray.length(); i++)
							{
								JSONObject simpleGoodsJsonObject = simpleGoodsJsonArray
										.getJSONObject(i);
								SIMPLEGOODS simplegoods = SIMPLEGOODS
										.fromJson(simpleGoodsJsonObject);
								simplegoodsList.add(simplegoods);
							}
						}

					}

				}

			}

		} catch (Exception e)
		{

			e.printStackTrace();
		}

	}

	public void goodsDataCache(String result)
	{

		try
		{
			if (result != null)
			{
				JSONObject jsonObject = new JSONObject(result);

				STATUS responseStatus = STATUS.fromJson(jsonObject
						.optJSONObject("status"));
				if (responseStatus.succeed == 1)
				{
					JSONArray categorygoodJsonArray = jsonObject
							.optJSONArray("data");
					if (null != categorygoodJsonArray
							&& categorygoodJsonArray.length() > 0)
					{
						categorygoodsList.clear();
						for (int i = 0; i < categorygoodJsonArray.length(); i++)
						{
							JSONObject categoryGoodsJsonObject = categorygoodJsonArray
									.getJSONObject(i);
							CATEGORYGOODS simplegoods = CATEGORYGOODS
									.fromJson(categoryGoodsJsonObject);
							categorygoodsList.add(simplegoods);
						}

					}
				}

			}

		} catch (Exception e)
		{

			e.printStackTrace();
		}

	}

	public void fei()
	{
		String url = ProtocolConst.fenlei;
		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>()
		{
			public void callback(String url, JSONObject jo, AjaxStatus status)
			{
				STATUS responseStatus;
				try
				{
					responseStatus = STATUS
							.fromJson(jo.optJSONObject("status"));
					if (responseStatus.succeed == 1)
					{
						JSONArray array = jo.getJSONArray("data");
						if (null != array && array.length() > 0)
						{
							for (int i = 0; i < array.length(); i++)
							{
								JSONObject playerJsonObject = array
										.getJSONObject(i);
								Fen playItem = Fen.fromJson(playerJsonObject);
								fen.add(playItem);
							}
						}
						HomeModel.this.OnMessageResponse(url, jo, status);
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		};
		cb.url(url).type(JSONObject.class);
		aq.ajax(cb);
	}

	public void tupian()
	{
		String url = ProtocolConst.SHOUYE;
		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>()
		{
			public void callback(String url, JSONObject jo, AjaxStatus status)
			{
				try
				{
					responseStatus = STATUS
							.fromJson(jo.optJSONObject("status"));
					if (responseStatus.succeed == 1)
					{
						JSONObject dataJsonObject = jo.optJSONObject("data");
						if (null != dataJsonObject)
						{

							JSONArray array = dataJsonObject
									.optJSONArray("ads");
							aCache.put("array", array);
							if (null != array && array.length() > 0)
							{
								viewp.clear();
								for (int i = 0; i < array.length(); i++)
								{
									JSONObject playerJsonObject = array
											.getJSONObject(i);
									ShouTu playItem = ShouTu
											.fromJson(playerJsonObject);
									viewp.add(playItem);
								}
							}

							JSONArray array1 = dataJsonObject
									.optJSONArray("recommend");
							aCache.put("recommens", array1);
							if (null != array1 && array1.length() > 0)
							{
								zuijian.clear();
								for (int i = 0; i < array1.length(); i++)
								{
									JSONObject playerJsonObject = array1
											.getJSONObject(i);
									Tuijian playItem = Tuijian
											.fromJson(playerJsonObject);
									zuijian.add(playItem);
								}
							}

							JSONArray array11 = dataJsonObject
									.optJSONArray("new");
							aCache.put("news", array11);
							if (null != array11 && array11.length() > 0)
							{
								shudao.clear();
								for (int i = 0; i < array11.length(); i++)
								{
									JSONObject playerJsonObject = array11
											.getJSONObject(i);
									News playItem = News
											.fromJson(playerJsonObject);
									shudao.add(playItem);
								}
							}

							JSONArray array2 = dataJsonObject
									.optJSONArray("hot");
							aCache.put("hots", array2);
							if (null != array2 && array2.length() > 0)
							{
								zuire.clear();
								for (int i = 0; i < array2.length(); i++)
								{
									JSONObject playerJsonObject = array2
											.getJSONObject(i);
									Home playItem = Home
											.fromJson(playerJsonObject);
									zuire.add(playItem);
								}
							}
							JSONArray array3 = dataJsonObject
									.optJSONArray("other_ads");
							aCache.put("other_ads", array3);
							if (null != array3 && array3.length() > 0)
							{
								adverts.clear();
								for (int i = 0; i < array3.length(); i++)
								{
									JSONArray playerJSONArray = array3
											.getJSONArray(i);
									if (playerJSONArray.length() > 0)
									{
										Advert playItem = Advert
												.fromJson(playerJSONArray
														.getJSONObject(0));
										adverts.add(playItem);
									}
								}
							}
							HomeModel.this.OnMessageResponse(url, jo, status);
						}
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		};
		cb.url(url).type(JSONObject.class);
		pd = new ProgressDialog(mContext);
		pd.setMessage(mContext.getResources().getString(R.string.hold_on));
		aq.progress(pd).ajax(cb);
		// aq.ajax(cb);
	}

	public void fetchHotSelling()
	{
		String url = ProtocolConst.HOMEDATA;

		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>()
		{

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status)
			{

				try
				{
					STATUS responseStatus = STATUS.fromJson(jo
							.optJSONObject("status"));
					if (responseStatus.succeed == 1)
					{
						fileSave(jo.toString(), "homeData");

						JSONObject dataJsonObject = jo.optJSONObject("data");
						if (null != dataJsonObject)
						{
							JSONArray playerJSONArray = dataJsonObject
									.optJSONArray("player");
							if (null != playerJSONArray
									&& playerJSONArray.length() > 0)
							{
								playersList.clear();
								for (int i = 0; i < playerJSONArray.length(); i++)
								{
									JSONObject playerJsonObject = playerJSONArray
											.getJSONObject(i);
									PLAYER playItem = PLAYER
											.fromJson(playerJsonObject);
									playersList.add(playItem);
								}
							}

							JSONArray simpleGoodsJsonArray = dataJsonObject
									.optJSONArray("promote_goods");

							if (null != simpleGoodsJsonArray
									&& simpleGoodsJsonArray.length() > 0)
							{
								simplegoodsList.clear();
								for (int i = 0; i < simpleGoodsJsonArray
										.length(); i++)
								{
									JSONObject simpleGoodsJsonObject = simpleGoodsJsonArray
											.getJSONObject(i);
									SIMPLEGOODS simplegoods = SIMPLEGOODS
											.fromJson(simpleGoodsJsonObject);
									simplegoodsList.add(simplegoods);
								}
							} else
							{
								simplegoodsList.clear();
							}

							HomeModel.this.OnMessageResponse(url, jo, status);

						}
					}

				} catch (JSONException e)
				{
				}

			}

		};

		cb.url(url).type(JSONObject.class);

		aq.ajax(cb);

	}

	public void fetchCategoryGoods()
	{
		String url = ProtocolConst.CATEGORYGOODS;

		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>()
		{

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status)
			{
				done(url, jo, status);
				try
				{
					STATUS responseStatus = STATUS.fromJson(jo
							.optJSONObject("status"));
					if (responseStatus.succeed == 1)
					{
						fileSave(jo.toString(), "goodsData");
						JSONArray categorygoodJsonArray = jo
								.optJSONArray("data");
						if (null != categorygoodJsonArray
								&& categorygoodJsonArray.length() > 0)
						{
							categorygoodsList.clear();
							for (int i = 0; i < categorygoodJsonArray.length(); i++)
							{
								JSONObject categoryGoodsJsonObject = categorygoodJsonArray
										.getJSONObject(i);
								CATEGORYGOODS simplegoods = CATEGORYGOODS
										.fromJson(categoryGoodsJsonObject);
								categorygoodsList.add(simplegoods);
							}
							HomeModel.this.OnMessageResponse(url, jo, status);
						} else
						{
							categorygoodsList.clear();
						}

					}

				} catch (JSONException e)
				{
				}

			}

		};

		cb.url(url).type(JSONObject.class);
		ProgressDialog pd = new ProgressDialog(mContext);
		pd.setMessage(mContext.getResources().getString(R.string.hold_on));
		aq.progress(pd).ajax(cb);
		// aq.ajax(cb);

	}

	protected void done(String url, JSONObject jo, AjaxStatus status)
	{
		String localUrl = url;
		JSONObject result = jo;
	}

	public String web;

	public void helpArticle(int article_id)
	{

		String url = ProtocolConst.ARTICLE;

		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>()
		{

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status)
			{

				HomeModel.this.callback(url, jo, status);

				try
				{
					STATUS responseStatus = STATUS.fromJson(jo
							.optJSONObject("status"));
					web = jo.getString("data").toString();

					HomeModel.this.OnMessageResponse(url, jo, status);

				} catch (JSONException e)
				{

					e.printStackTrace();
				}

			}

		};

		SESSION session = SESSION.getInstance();

		JSONObject requestJsonObject = new JSONObject();

		Map<String, String> params = new HashMap<String, String>();
		try
		{
			requestJsonObject.put("session", session.toJson());
			requestJsonObject.put("article_id", article_id);
		} catch (JSONException e)
		{
			// TODO: handle exception
		}

		params.put("json", requestJsonObject.toString());

		cb.url(url).type(JSONObject.class).params(params);
		aq.ajax(cb);

	}

	// 缓存数据
	private PrintStream ps = null;

	public void fileSave(String result, String name)
	{

		String path = rootpath + "/" + pkName;

		File filePath = new File(path);
		if (!filePath.exists())
		{
			filePath.mkdirs();
		}

		File file = new File(filePath + "/" + name + ".dat");
		FileOutputStream fos = null;
		try
		{
			fos = new FileOutputStream(file);
			ps = new PrintStream(fos);
			ps.print(result);
			ps.close();
			fos.close();
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

}
